package com.gitee.ywj1352.learning.ag.zuul.utils;

import com.gitee.ywj1352.lerning.ag.common.constants.UserConstants;
import io.jsonwebtoken.*;
import org.joda.time.DateTime;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;


/**
 * Created by ywj on 2018/2/12.
 */
@Component
public class JwtUtil {
    private static org.slf4j.Logger logger= LoggerFactory.getLogger(JwtUtil.class);

    @Value("${jwt.key-pub.path}")
    private String pubKey;

    @Value("${jwt.key-pri.path}")
    private String priKey;
    @Value("${jwt.expireTime}")
    private int expireTime;

    //name,acount(username),userId,expire
    public String generateToken(JwtInfo jwtInfo) {

        String compactJws = null;
        try {
            String userName=jwtInfo.getUserName();
            String userId=jwtInfo.getUserId();
            String name=jwtInfo.getName();
            compactJws = Jwts.builder()
                    .setSubject(userName).claim(UserConstants.USER_ID.toString(),userId)
                    .claim(UserConstants.USER_NAME.toString(),userName)
                    .claim(UserConstants.NAME.toString(),name)
                    .setExpiration(DateTime.now().plusSeconds(expireTime).toDate())
                    .signWith(SignatureAlgorithm.RS256, KeyHelper.getPrivateKey(priKey))
                    .compact();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return compactJws;
    }


    public Jws<Claims> passToken(String token)  {
        try {
            //在parser的时候 如果 时间超时 也会抛异常
            Jws<Claims> claimsJws = Jwts.parser().setSigningKey(KeyHelper.getPublicKey(pubKey)).parseClaimsJws(token);
            return claimsJws;
        } catch (Exception e) {
            logger.error("jwt token is wrong,Token is{}",token);
            e.printStackTrace();
            return null;
        }
    }

    /**
     * 解析token成为JwtInfo
     * @param token
     * @return
     */
    public JwtInfo getInfoFromToken(String token){
        try {
            //在parser的时候 如果 时间超时 也会抛异常
            Jws<Claims> claimsJws = passToken(token);
            JwtInfo jwtInfo = new JwtInfo();
            jwtInfo.setName((String) claimsJws.getBody().get(UserConstants.NAME.toString()));
            jwtInfo.setUserName((String) claimsJws.getBody().get(UserConstants.USER_NAME.toString()));
            jwtInfo.setUserId((String) claimsJws.getBody().get(UserConstants.USER_ID.toString()));
            return jwtInfo;
        } catch (Exception e) {
            logger.error("jwt token is wrong,Token is{}",token);
            e.printStackTrace();
            return null;
        }
    }


}
